package org.example.ch04.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * ClassName: MybatisUtils
 * Description:
 *
 * @Author zjl
 * @Create 2025/04/22 10:08
 * @Version 1.0
 */
public class MybatisUtils {
    /**
     * 声明SqlSessionFactory, 用于创建SqlSession
     */
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 类加载时在静态代码块完成初始化
     */
    static {
        try {
            // 读取mybatis.xml文件并返回一个输入流
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            //通过SqlSessionFactoryBuilder类来解析流的数据并初始化SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建SqlSession对象
     * 如果autoCommit为true, 则表示自动提交事务, 否则手动提交事务
     * @return
     */
    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }

    /**
     * 默认获取自动提交事务的SqlSession
     * @return
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }
}
